#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

#include "head.h"
int hass_fd, acceptfd;
MSG_t msg;//保存hass采集发送的信息

void *thread(void *arg)
{
    int recvbyte;
    MSG_t recv_msg;
    while (1)
    {
        recvbyte = recv(acceptfd, &recv_msg, sizeof(recv_msg), 0);
        if (recvbyte < 0)
        {
            perror("recv error.");
            // return NULL;
        }
        printf("qt-recv:%s %d %d %f %s\n", recv_msg.name, recv_msg.type, recv_msg.ival, recv_msg.fval,recv_msg.text);
    }
    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
#if 1
    if (argc != 3)
    {
        printf("please input %s <hassserver_ip> <hassserver_port>\n", argv[0]);
        return -1;
    }
    hass_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (hass_fd < 0)
    {
        perror("socket error.");
        return -1;
    }
    struct sockaddr_in hassqtServeraddr, clientaddr;
    //1》填充hass通信server端结构体
    hassqtServeraddr.sin_family = AF_INET;
    hassqtServeraddr.sin_port = htons(atoi(argv[2]));
    hassqtServeraddr.sin_addr.s_addr = inet_addr("0.0.0.0");

    socklen_t len = sizeof(struct sockaddr_in);

    if (bind(hass_fd, (struct sockaddr *)&hassqtServeraddr, len) < 0)
    {
        perror("connect error.");
        return -1;
    }

    if (listen(hass_fd, 5) < 0)
    {
        perror("listen error.");
        return -1;
    }

    acceptfd = accept(hass_fd, (struct sockaddr *)&clientaddr, &len);
    if (acceptfd < 0)
    {
        perror("accept error.");
        return -1;
    }
    printf("ip:%s port:%d\n", (char *)inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));

    pthread_t tid;
    pthread_create(&tid, NULL, thread, NULL);
    pthread_detach(tid);

#endif
    strcpy(msg.name, "temp");
    strcpy(msg.text, "temp !!!!!!!!!");
    srand((float)time(NULL));
    while (1)
    {
        msg.type = rand() % 2;
        msg.type++;
        msg.ival = rand() % 2;
        msg.fval = rand() % 1000 + ((float)(rand() % 1001) * 0.001f); //获取0-10000随机小数
        send(acceptfd, &msg, sizeof(msg), 0);
      //  printf("qt-send:%s %d %d %f %s\n", msg.name, msg.type, msg.ival, msg.fval,msg.text);
        sleep(1);
    }

    return 0;
}
